#include "appexitio.h"

#ifdef WIN32
#include <windows.h>
#else
#include <stdlib.h>
#endif
#include <string>
#include "Log.h"

namespace GlobalVar {
	extern bool exitFlag;
};

#ifdef WIN32
bool ctrlhandler(unsigned long fdwctrltype)
{
	bool exitEvent = false;
	switch (fdwctrltype)
	{
		// handle the ctrl-c signal.
	case CTRL_C_EVENT:
		printf("ctrl-c event\n\n");
		exitEvent = true;
		break;
		// ctrl-close: confirm that the user wants to exit.
	case CTRL_CLOSE_EVENT:
		printf("ctrl-close event\n\n");
		exitEvent = true;
		break;
		// pass other signals to the next handler.
	case CTRL_BREAK_EVENT:
		printf("ctrl-break event\n\n");
		break;
	case CTRL_LOGOFF_EVENT:
		printf("ctrl-logoff event\n\n");
		break;
	case CTRL_SHUTDOWN_EVENT:
		printf("ctrl-shutdown event\n\n");
		exitEvent = true;
		//清理
		break;
	default:
		break;
	}
	if (exitEvent)
	{
		Sleep(10);
	}
	GlobalVar::exitFlag = exitEvent;
	return exitEvent;
}
#else
SignalHandler::SignalHandler()
{
	/** install signal use sigaction **/
	struct sigaction act;
	sigemptyset(&act.sa_mask);   /** 清空阻塞信号 **/
	act.sa_flags = SA_SIGINFO;     /** 设置SA_SIGINFO 表示传递附加信息到触发函数 **/
	act.sa_sigaction = handle_signal;
	if (sigaction(SIGHUP, &act, NULL) < 0      // 1
		|| sigaction(SIGINT, &act, NULL) < 0  // 2
		|| sigaction(SIGQUIT, &act, NULL) < 0 // 3
											  //|| sigaction(SIGKILL,&act,NULL) < 0 // 9
		|| sigaction(SIGTERM, &act, NULL) < 0 // 15
		)
	{
		CLogger::createInstance()->Log(MsgInfo, "install signal handler error");
	}
};

void SignalHandler::printf_out()
{

}

void SignalHandler::handle_signal(int n, siginfo_t *siginfo, void *myact)
{
	CLogger::createInstance()->Log(MsgInfo
		, "SIGNAL received: signo=%d errno=%d code=%d "
		, siginfo->si_signo, siginfo->si_errno, siginfo->si_code);
	if (siginfo->si_signo == 1
		|| siginfo->si_signo == 2
		|| siginfo->si_signo == 3
		|| siginfo->si_signo == 9
		|| siginfo->si_signo == 15)
	{
		//程序退出，进行退出处理操作
		//G_VALUE::watchDogRunning = false;
		usleep(10000);
		exit(0);
	}
};
#endif // WIN32
